//
//  UIImage+Extension.swift
//  66.照片选择器
//
//  Created by apple on 16/3/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

extension UIImage {
    
    /**
     等比例缩小图片
     
     - returns: 缩小后图片
     */
    func scaleImage(newWidth: CGFloat = 300) -> UIImage {
        
        if size.width < newWidth {
            return self
        }

        //公式: newHeight / newWidth = height / width
        let newHeight = newWidth * size.height / size.width
        
        // 绘图开启图片上下文
        UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
        
        // 画图
        self.drawInRect(CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        
        // 获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        // 关闭上下文
        UIGraphicsEndImageContext()
        
        return image
    }
}
